<template>
<view class="box">
    <view class="live-left">
        <view class="live-title">末日双人成行官方职业联赛 成都AG Vs 广州TTG  <span style="color:red">直播中.</span></view>
        <view class="video-container">
            <video id="my-player" class="video-js vjs-default-skin" controls preload="auto" 
                   :poster="posterUrl">
                <source :src="options.src" type="application/x-mpegURL">
            </video>
        </view>
		<view class="userInfo">
			<view class="gift-item-money">
				<view>钱包：{{userInfo.money}}</view>
				<view>贡献：{{userInfo.contribution}}</view>
				<view>等级：Lv{{userInfo.grade}}</view>
				<view>经验：{{userInfo.experience}}</view>
				<view>升级经验：{{ experienceCalculator(userInfo.grade) }}</view>
			</view>
		</view>
        <view class="gift-area">
			<view class="gift-item" v-for="(item,index) in giftList" @click="sendGift" :data-obj="item">
				<image :src="item.img"></image>
				<view class="gift-money">{{item.money}}末日币</view>
				<view class="gift-name">{{item.name}}</view>
			</view>
		</view>
    </view>
    <view class="live-right">
		<!-- 礼物 排行榜 -->
		<view class="gift-ranking">
			<view class="ranking-info">
				<view class="r-left">昵称</view>
				<view class="r-right">互动值</view>
			</view>
			<view class="ranking-info" v-for="(item,index) in giftRanking">
				<view class="r-left">
					<image class="r-img" v-if="index == 0" src=""></image>
					<image class="r-img" v-else-if="index == 1" src=""></image>
					<image class="r-img" v-else-if="index == 2" src=""></image>
					<view class="r-img-2" v-else>{{ index + 1 }}</view>
					<view>Lv{{item.grade}} {{item.nickname}}</view>
				</view>
				<view class="r-right">{{item.contribution}}互动值</view>
			</view>
		</view>
		
		<!-- 礼物区域 -->
		<view class="gift-box">
			
		</view>
		
		<!-- 换成官方直播间的发送和订阅 -->
		<WorldChatBox 
		subscribeTopic="/game/officialLiveBroadcast" 
		sendTopic="/mori/officialLiveBroadcast"
		boxWidth="100%"
		boxHeight="100vh"
		boxBackgroundColor="#fff"></WorldChatBox>
	</view>
</view>
</template>

<script>
import { getAllGift } from "@/api/gift.js";
import WorldChatBox from "@/component/WorldChatBox.vue"
import { getUserInfo,givingGifts,giftRanking } from "@/api/live.js";

	
export default {
	
    data() {
        return {
			giftList:[],
			giftRanking:[
				{"name":"张三","lv":"11","rewardValue":"900"},
			],
            options: {
                src: "http://192.168.0.151:7788/live/666/hls.m3u8"
            },
            posterUrl: "https://picsum.photos/1920/1080?random=1",
            player: null,
			userInfo:{},
        }
    },
	components:{
		WorldChatBox
	},
    onShow() {
		this.getGift();
        this.initVideoPlayer();
    },
    onHide() {
        this.destroyVideoPlayer();
    },
	mounted(){
		//获取个人信息
		this.setUserInfo();
		//排行榜数据
		this.getGiftRanking();
		setInterval(()=>{
			this.getGiftRanking();
		},8000);
	},
    methods: {
		//获取排行方法 giftRanking
		getGiftRanking(){
			giftRanking().then((data)=>{
				console.log("排行榜数据",data);
				this.giftRanking = data.data.records
			});
		},
		//经验计算器
		experienceCalculator(n){
			let a = n;
			// 等级 * 等级 * 100 + 等级 = 当前等级升级需要的经验
			let b = a * a * 100 + a
			return b;
		},
		//获取用户个人信息并赋值到页面上
		setUserInfo(){
			getUserInfo().then((data)=>{
				console.log("响应结果",data);
				this.userInfo = data.data;
			})
		},
		//点击发送礼物
		sendGift(e){
			console.log("礼物",e);
			//获取礼物id
			let giftId = e.currentTarget.dataset.obj.id;
			//把礼物id发给后端
			givingGifts(giftId).then((data)=>{
				console.log("结果",data);
				//重新获取一下用户个人信息
				this.setUserInfo();
				
				if(data.code == 200){
					// 广播给所有人，有人刷礼物了
					const message = {
					  code:2, // 礼物通知
					  id: this.userInfo?.id,
					  avatar: this.userInfo?.avatar || '',
					  nickname: this.userInfo?.nickname || '匿名用户',
					  level: this.userInfo?.level || 1,
					  gender: this.userInfo?.sex,
					  giftObj:data.data
					};
					client.send("/mori/officialLiveBroadcast", {}, JSON.stringify(message));
					
					//排行榜数据
					this.getGiftRanking();
				}else{
					uni.showToast({
					    title: '余额不足请充值',
					    icon: 'error',
					    duration: 2000
					});
				}

			});
		},
		getGift(){
			getAllGift().then((data)=>{
				this.giftList = data.data;
			});
		},
        initVideoPlayer() {
            // 检查Video.js是否加载成功
            if (window.videojs) {
                // 初始化播放器
                this.player = videojs('my-player');
                
                // 播放器准备就绪回调
                this.player.ready(() => {
                    console.log('Video.js播放器初始化成功');
                    
                    // 优化性能
                    this.player.tech_.off('mousemove');
                    
                    // 显示加载状态
                    this.player.on('waiting', () => {
                        this.player.addClass('vjs-waiting');
                    });
                    this.player.on('playing', () => {
                        this.player.removeClass('vjs-waiting');
                    });
                    
                    // 设置自定义错误提示
                    this.player.on('error', () => {
                        const error = this.player.error();
                        if (error) {
                            console.error('播放器错误:', error);
                        }
                    });
                    
                    // 检查HLS支持
                    this.setupHlsPlayer();
                });
            } else {
                console.error('Video.js加载失败');
            }
        },
        
        setupHlsPlayer() {
            if (window.Hls) {
                // 使用hls.js
                const hls = new Hls({
                    maxBufferLength: 30,
                    maxMaxBufferLength: 60,
                    startFragPrefetch: true
                });
                
                hls.loadSource(this.options.src);
                hls.attachMedia(this.player.tech_.el().querySelector('video'));
                
                // 事件监听
                hls.on(Hls.Events.MANIFEST_PARSED, () => {
                    console.log('HLS清单解析成功');
                    this.player.play().catch(err => {
                        console.error('自动播放失败:', err);
                    });
                });
                
                // 错误处理
                hls.on(Hls.Events.ERROR, (event, data) => {
                    console.error('HLS错误:', data);
                    if (data.fatal) {
                        switch(data.type) {
                            case Hls.ErrorTypes.NETWORK_ERROR:
                                hls.startLoad();
                                break;
                            case Hls.ErrorTypes.MEDIA_ERROR:
                                hls.recoverMediaError();
                                break;
                            default:
                                this.handlePlayerError('HLS播放错误: ' + data.details);
                                hls.destroy();
                                break;
                        }
                    }
                });
                
                // 存储hls实例引用，便于销毁
                this.player.hls = hls;
            } else if (this.player.canPlayType('application/x-mpegURL')) {
                // 浏览器原生支持HLS
                console.log('浏览器原生支持HLS播放');
                this.player.src({ type: 'application/x-mpegURL', src: this.options.src });
                this.player.play().catch(err => {
                    console.error('自动播放失败:', err);
                });
            } else {
                this.handlePlayerError('当前浏览器不支持HLS播放');
            }
        },
        
        handlePlayerError(message) {
            if (this.player) {
                this.player.error({
                    code: 4,
                    message: message || '播放错误，请检查网络连接或直播地址'
                });
            }
            console.error(message);
        },
        
        destroyVideoPlayer() {
            if (this.player) {
                // 销毁HLS实例
                if (this.player.hls) {
                    this.player.hls.destroy();
                    delete this.player.hls;
                }
                
                // 销毁Video.js播放器
                this.player.dispose();
                this.player = null;
            }
        }
    }
}
</script>

<style scoped>
.box {
    width: 100%;
    height: 100vh;
    display: flex;
    justify-content: space-between;
    position: absolute;
}

.live-left {
    width: 78%;
    height: 100%;
    display: flex;
    flex-direction: column;
}

.live-title {
    height: 3vh;
	line-height: 3vh;
    background-color: #f0f0f0;
    padding: 10px;
    font-weight: bold;
	font-size: 12px;
}

.video-container {
    height: 78vh;
    width: 100%;
    position: relative;
    background-color: #000;
}

#my-player {
    width: 100%;
    height: 100%;
}

/* 自定义加载状态 */
.vjs-loading-spinner {
    border-color: rgba(255, 255, 255, 0.3);
    border-top-color: white;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.gift-area {
    background-color: #f8f8f8;
    border-top: 1px solid #eee;
    /* padding: 1vh 10px; */
	display: flex;
	gap: 2px;
	overflow-y: auto;
	flex: 1;
}

.live-right {
    width: 21.5%;
    height: 100%;
    background-color: #f5f5f5;
    border-left: 1px solid #eee;
}
.userInfo{
	width: 100%;
	height: 10px;
}
.gift-item-money{
	display: flex;
	flex-direction: row;
	align-items: stretch;
	padding-left: 7px;
	gap: 2px;
}
.gift-item-money > view{
	font-size: 7px;
	padding: 1px 5px;
	color: #231802;
	border-right: 1px solid #939393;
/* 	background-color: #c1191b; */
}
.gift-item{
	width: 50px;
	text-align: center;
	cursor: pointer;
}
.gift-item > image{
	width: 30px;
	height: 30px;
}
.gift-money{
	font-size: 6px;
	color: #c1191b;
}
.gift-name{
	font-size: 7px;
	color: #66430c;
}

/* 排行榜 */
.gift-ranking{
	width: 21.5%;
	height: 30vh;
	background-color: #ffffff;
	position: absolute;
	top: 0;
	z-index: 99999;
	border-radius: 0 0 10px 10px;
	overflow-y: auto;
}
.ranking-info{
	width: 90%;
	padding: 0 5%;
	height: 20px;
	display: flex;
	font-size: 8px;
	line-height: 20px;
}
.r-img{
	width: 10px;
	height: 10px;
	margin-top: 5px;
	margin-right: 5px;
}
.r-img-2{
	width: 10px;
	height: 10px;
	background-image: url("");
	background-size: 100% 100%;
	color: #ffffff;
	font-size: 5px;
	text-align: center;
	line-height: 10px;
	margin-top: 5px;
	margin-right: 5px;
}

.r-left{
	width: 60%;
	display: flex;
}
.r-right{
	width: 40%;
	text-align: right;
}

.gift-box{
	width: 21.5%;
	height: 30px;
	position: absolute;
	top: 35vh;
	z-index: 99999;
	background-image: url("");
	background-size: 100% 100%;
}
</style>  